package com.lp.juc;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

public class MultiTaskTest {
    private static class Task<String> implements Callable<String>{
        private String s;
        public Task(String s){
            this.s = s;
        }
        @Override
        public String call() throws Exception {
            StringBuffer sb = new StringBuffer();
            sb.append(this.s);
            //System.out.println(sb.toString());
            return (String) sb.toString();
        }
    }
    public static <T> List<T> multiTask(int n, FutureTask<T> futureTask, int num){
        ExecutorService exec = Executors.newFixedThreadPool(n);
        List<FutureTask<T>> taskList = new ArrayList<>();
        for (int i=0;i<num;i++) {
            taskList.add(futureTask);
            exec.submit(futureTask);
            exec.execute(futureTask);
        }
        List<T> result = new ArrayList<>();
        for (FutureTask<T> ft: taskList) {
            try{
                result.add(ft.get());
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        exec.shutdown();
        return result;
    }

    public static void main(String[] args) throws Exception {
//        FutureTask ft1 = new FutureTask(new Task("测试"));
//        Thread t1 = new Thread(ft1);
//        t1.start();
        int n = 100000;
        List<String> list1 = new ArrayList<>();
        long l1 = System.currentTimeMillis();
        while (n > -1){
            FutureTask ft = new FutureTask(new Task("测试"+n));
            Thread t = new Thread(ft);
            t.start();
            String s = (String)ft.get();
            list1.add(s);
            n--;
        }
        long l2 = System.currentTimeMillis();
        System.out.println(l2-l1);
        //System.out.println(list1);
        List<String> list2 = new ArrayList<>();
        long l3 = System.currentTimeMillis();
        list2 = multiTask(5, new FutureTask(new Task("测试" + n)), 100000);
        long l4 = System.currentTimeMillis();
        System.out.println(l4-l3);
        //System.out.println(list2);
    }
}
